package com.zjsru.oneDay202206;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Author: likew
 * @Date: 2022/6/29
 *
 *  TinyURL 的加密与解密
 *  输入：url = "https://leetcode.com/problems/design-tinyurl"
 *  输出："https://leetcode.com/problems/design-tinyurl"
 *
 * 解释：
 * Solution obj = new Solution();
 * string tiny = obj.encode(url); // 返回加密后得到的 TinyURL 。
 * string ans = obj.decode(tiny); // 返回解密后得到的原本的 URL 。
 *
 */
public class Codec {
    Map<String, String> origin2Tiny = new HashMap<>(), tiny2Origin = new HashMap<>();
    String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    String prefix = "https://acoier.com/tags/";
    int k = 6;
    Random random = new Random();
    
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        while(!origin2Tiny.containsKey(longUrl)){
            char[] cs = new char[k];
            for (int i = 0; i < k; i++) {
                cs[i] = str.charAt(random.nextInt(str.length()));
                String cur = prefix + String.valueOf(cs);
                if(tiny2Origin.containsKey(cur)) continue;
                tiny2Origin.put(cur,longUrl);
                origin2Tiny.put(longUrl,cur);
            }
        }
        return origin2Tiny.get(longUrl);
    }
    
    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return tiny2Origin.get(shortUrl);
    }
    
    public static void main(String[] args) {
        Codec codec = new Codec();
        String longUrl = "https://leetcode.com/problems/design-tinyurl";
        String shortUrl = "https://leetcode.com/problems/design-tinyurl";
        System.out.println(codec.encode(longUrl));
        System.out.println(codec.decode(shortUrl));
    }
}
